﻿-- =============================================
-- Author:		David Settino
-- Create date: 12/30/2010
-- Description:	Converts circle or location string data type
--    to geography data type before insert
-- =============================================
CREATE TRIGGER [dbo].[TargetAreaInsert] 
ON [dbo].[TargetArea]
AFTER INSERT AS
BEGIN
  DECLARE @id int
  DECLARE @Circle VARCHAR(500)
  DECLARE @Polygon [geography]
  DECLARE @Location VARCHAR(500)

  SET @Circle = (SELECT Circle FROM inserted)
  IF (@Circle IS NOT NULL)
    SET @Polygon = [dbo].[CircleToGeography](@Circle)
  ELSE
    BEGIN
      SET @Location = (SELECT Location FROM inserted)
      IF (@Location IS NOT NULL)
        BEGIN
          SET @Polygon = geography::STGeomFromText(@Location,4326)
        END
    END 
  SET @id = (SELECT ID  FROM inserted)
  UPDATE [dbo].[TargetArea]
  SET Polygon = @Polygon
  WHERE id = @id
END